package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.model.LSRInfo;
import com.maiarstar.e101.protocol.cerebellum.api.model.LSTInfo;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolSetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class LS_Test_Activity extends AppCompatActivity {
    private static final String TAG = "LS_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    private static Handler handler_refresh_status_task;
    private static Runnable run_refresh_status_task;
    SeekBar seekBar_LST;
    TextView tV_LST_Set, tV_LSR_Get;
    Button btn_LSR_Reset, btn_LS_Pass, btn_LS_Fail;
    double LSR_dutyPersent, LSR_freq;
    int LSR_overFlow_Cnt;
    long LSR_cnt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_ls_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        seekBar_LST = findViewById(R.id.seekBar_LST);
        tV_LST_Set = findViewById(R.id.tV_LST_Set);
        tV_LSR_Get = findViewById(R.id.tV_LSR_Get);
        initCerebellumManager();

        Factory_LS_BTN();
        Factory_LS_SB(seekBar_LST, tV_LST_Set);
        Refresh_Status_Task_Init();
    }

    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();
        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }

    private void Factory_LS_BTN(){
        btn_LS_Pass = findViewById(R.id.btn_LS_Pass);
        btn_LS_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("LS", "通过");
                if (editor.commit()) {
                    Toast.makeText(LS_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LS_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                } else {
                    Toast.makeText(LS_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_LS_Fail = findViewById(R.id.btn_LS_Fail);
        btn_LS_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("LS", "未通过");
                if (editor.commit()) {
                    Toast.makeText(LS_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LS_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                } else {
                    Toast.makeText(LS_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        btn_LSR_Reset = findViewById(R.id.btn_LSR_Reset);
        btn_LSR_Reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //GetLSR();
                if(SetLSR()){
                    Toast.makeText(LS_Test_Activity.this, "清除成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LS_Test_Activity.this, "清除失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void Factory_LS_SB(SeekBar seekBar, TextView textView){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int dutyPersent = 0;
            String textView_str = "激光发射器值：";
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                switch (progress){
                    case 0:{
                        dutyPersent = 0;
                        break;
                    }
                    case 1:{
                        dutyPersent = 50;
                        break;
                    }
                    case 2: {
                        dutyPersent = 100;
                        break;
                    }
                    default:
                        break;
                }
                textView_str = "激光发射器值："+dutyPersent+"%";
                textView.setText(textView_str);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(SetLST(dutyPersent)){
                    Toast.makeText(LS_Test_Activity.this, textView_str+"设定成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LS_Test_Activity.this, textView_str+"设定失败", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
    private boolean SetLST(int dutyPersent) throws ProtocolException {
        try {
            LSTInfo lstInfo = new LSTInfo();
            lstInfo.setDutyCycle(dutyPersent);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            return setter.setLSTInfo(lstInfo);
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }
    private boolean GetLSR() throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            LSR_dutyPersent = getter.getLSRInfo().getDutyCycle();
            LSR_freq = getter.getLSRInfo().getFrequency();
            LSR_overFlow_Cnt = getter.getLSRInfo().getOverflowCount();
            LSR_cnt = getter.getLSRInfo().getCount();
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }


    private void Refresh_Status_Task_Init(){
        handler_refresh_status_task = new Handler(Looper.getMainLooper());//新建任务
        run_refresh_status_task = new Runnable() {
            @Override
            public void run() {
                handler_refresh_status_task.postDelayed(this, 2000);
                if(GetLSR()){
                    tV_LSR_Get.setText("激光接收器：" + LSR_dutyPersent+"%" + LSR_freq+"Hz" + "   溢出次数："+LSR_overFlow_Cnt + "    计数："+LSR_cnt);
                }else{
                    tV_LSR_Get.setText("激光接收器 - 异常 - ："+ LSR_dutyPersent+"%" + LSR_freq+"Hz" + "   溢出次数："+LSR_overFlow_Cnt + "    计数："+LSR_cnt);
                }
                //Log.d(TAG, "Refresh_Status_Cycle:in");
            }
        };
        handler_refresh_status_task.post(run_refresh_status_task);//启动任务
        //Log.d(TAG, "Refresh_Status_Cycle:out");
    }
    private boolean SetLSR() throws ProtocolException {
        try {
            LSRInfo lsrInfo = new LSRInfo();
            //lsrInfo.setCount(0);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            return setter.setLSRInfo(lsrInfo);
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(LS_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
        finish();
        Toast.makeText(LS_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }


}